//! Flight SQL错误处理
//! 
//! 定义Flight SQL服务的错误类型和处理机制

use thiserror::Error;

/// Flight SQL错误类型
#[derive(Error, Debug)]
pub enum FlightSqlError {
    #[error("Arrow错误: {0}")]
    Arrow(#[from] arrow::error::ArrowError),
    
    #[error("Flight错误: {0}")]
    Flight(#[from] arrow_flight::error::FlightError),
    
    #[error("Tonic错误: {0}")]
    Tonic(#[from] tonic::Status),
    
    #[error("内核错误: {0}")]
    Kernel(#[from] data_gateway_kernel::error::KernelError),
    
    #[error("序列化错误: {0}")]
    Serialization(#[from] serde_json::Error),
    
    #[error("查询执行错误: {message}")]
    QueryExecution { message: String },
    
    #[error("协议错误: {message}")]
    Protocol { message: String },
    
    #[error("认证错误: {message}")]
    Authentication { message: String },
    
    #[error("授权错误: {message}")]
    Authorization { message: String },
    
    #[error("内部错误: {message}")]
    Internal { message: String },
}

impl FlightSqlError {
    /// 创建查询执行错误
    pub fn query_execution(message: impl Into<String>) -> Self {
        Self::QueryExecution {
            message: message.into(),
        }
    }
    
    /// 创建协议错误
    pub fn protocol(message: impl Into<String>) -> Self {
        Self::Protocol {
            message: message.into(),
        }
    }
    
    /// 创建认证错误
    pub fn authentication(message: impl Into<String>) -> Self {
        Self::Authentication {
            message: message.into(),
        }
    }
    
    /// 创建授权错误
    pub fn authorization(message: impl Into<String>) -> Self {
        Self::Authorization {
            message: message.into(),
        }
    }
    
    /// 创建内部错误
    pub fn internal(message: impl Into<String>) -> Self {
        Self::Internal {
            message: message.into(),
        }
    }
}

impl From<FlightSqlError> for tonic::Status {
    fn from(err: FlightSqlError) -> Self {
        match err {
            FlightSqlError::Authentication { message } => {
                tonic::Status::unauthenticated(message)
            }
            FlightSqlError::Authorization { message } => {
                tonic::Status::permission_denied(message)
            }
            FlightSqlError::QueryExecution { message } => {
                tonic::Status::invalid_argument(message)
            }
            FlightSqlError::Protocol { message } => {
                tonic::Status::invalid_argument(message)
            }
            FlightSqlError::Tonic(status) => status,
            _ => tonic::Status::internal(err.to_string()),
        }
    }
}

/// Flight SQL结果类型
pub type Result<T> = std::result::Result<T, FlightSqlError>;
